import java.util.*;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by codeczx on 2018/3/22.
 */
public class TrackingExecutor extends AbstractExecutorService {

    private ExecutorService exec;
    private Set<Runnable> taskCancelAtShutdown = Collections.synchronizedSet(new HashSet<>());

    TrackingExecutor(ExecutorService exec){
        this.exec = exec;
    }

    @Override
    public void shutdown() {
        exec.shutdown();
    }

    @Override
    public List<Runnable> shutdownNow() {
        return exec.shutdownNow();
    }

    @Override
    public boolean isShutdown() {
        return exec.isShutdown();
    }

    @Override
    public boolean isTerminated() {
        return exec.isTerminated();
    }

    @Override
    public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
        return exec.awaitTermination(timeout,unit);
    }

    @Override
    public void execute(Runnable command) {
        exec.execute(new Runnable() {
            @Override
            public void run() {
                try{
                    command.run();
                }finally {
                    if(isShutdown()&&Thread.currentThread().isInterrupted()){
                        taskCancelAtShutdown.add(command);
                    }
                }
            }
        });
    }

    public List<Runnable> getCanceledTask(){
        if(!exec.isTerminated()){
            throw new IllegalStateException("executor hasn't been terminated");
        }else{
            return new ArrayList<>(taskCancelAtShutdown);
        }
    }
}
